// 新增待办弹窗组件
import React, { useEffect } from 'react'
import useKeepState from 'use-keep-state'
import { isBefore } from '../../../../utils/date'
import { createTask } from '../../../../request/todaytask'
import { Modal, Form, Input, DatePicker, Rate } from 'antd'

type Props = {
  visible: boolean
  data?: object
  onSuccess: (res?: any) => void
  onCancel: () => void
}

const DATE_FORMAT = 'YYYY-MM-DD HH:mm:ss'
const { TextArea } = Input
const initialState = {
  confirmLoading: false,
}

const CreateTaskModal: React.FC<Props> = function ({
  visible,
  onSuccess,
  onCancel,
}: Props) {
  const [form] = Form.useForm()
  const [state, setState] = useKeepState(initialState)

  async function handleSubmitForm() {
    try {
      const values = await form.validateFields()
      const params = {
        date: values.date.format(DATE_FORMAT),
        content: values.content.trim(),
        count: values.count,
      }
      setState({ confirmLoading: true })

      createTask(params)
        .then(res => {
          if (res.data.success) onSuccess()
        })
        .finally(() => {
          setState({ confirmLoading: false })
        })
    } catch {}
  }
  useEffect(() => {
    if (!visible) form.resetFields()
  }, [visible])

  return (
    <Modal
      title="新增"
      visible={visible}
      onOk={handleSubmitForm}
      onCancel={onCancel}
      confirmLoading={state.confirmLoading}
      forceRender
      maskClosable={false}
    >
      <Form form={form}>
        <Form.Item
          label="开始日期"
          name="date"
          rules={[{ required: true, message: '请选择日期' }]}
        >
          {/* global.scss w100 : width: 100%; */}
          <DatePicker
            className="w100"
            allowClear
            disabledDate={isBefore}
          ></DatePicker>
        </Form.Item>
        <Form.Item
          label="任务内容"
          name="content"
          rules={[{ required: true, message: '请输入内容', whitespace: true }]}
        >
          <TextArea
            rows={3}
            maxLength={200}
            placeholder="请输入内容"
          ></TextArea>
        </Form.Item>
        <Form.Item
          label="优先级别"
          name="count"
          initialValue={5}
          rules={[{ required: true, message: '请选择优先级' }]}
        >
          <Rate></Rate>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default React.memo(CreateTaskModal)
